package com.yeskery.nut.bind.handler;

import com.yeskery.nut.annotation.web.CookieValue;
import com.yeskery.nut.bind.AnnotationBindObject;
import com.yeskery.nut.bind.FitValueHelper;
import com.yeskery.nut.bind.MethodParamHandler;
import com.yeskery.nut.core.Cookie;
import com.yeskery.nut.core.Execution;
import com.yeskery.nut.core.Request;
import com.yeskery.nut.scan.controller.AnnotationRequestMethodAttributes;
import com.yeskery.nut.util.StringUtils;

import java.lang.annotation.Annotation;
import java.lang.reflect.Parameter;

/**
 * CookieValue方法参数对象处理接口
 * @author sprout
 * 2022-06-11 15:58
 */
public class CookieValueMethodParamHandler implements MethodParamHandler {

    @Override
    public AnnotationBindObject handle(AnnotationRequestMethodAttributes attributes, Annotation annotation, Parameter parameter, Request request, Execution execution) {
        CookieValue cookieValue = (CookieValue) annotation;
        String name = cookieValue.value();
        if (StringUtils.isEmpty(name)) {
            name = parameter.getName();
        }
        String value = null;
        for (Cookie cookie : request.getCookies()) {
            if (cookie.getName().equals(name)) {
                value = cookie.getValue();
                break;
            }
        }
        return new AnnotationBindObject(FitValueHelper.getInstance().getFitParamValue(name, value, parameter.getType()),
                CookieValue.class, cookieValue.required(), cookieValue.value());
    }
}
